﻿#include "Receiver.h"
#include "MulticastSourceOption_v4.h"

Receiver::Receiver(asio::io_context& context, const asio::ip::address& listen_addr, const asio::ip::address& multicast_addr)
	: socket_(context)
{
	//asio::ip::udp::endpoint listen_endpoint(listen_addr, multicast_port_);
	//socket_.open(listen_endpoint.protocol());
	//socket_.set_option(asio::ip::udp::socket::reuse_address(true));
	//socket_.bind(listen_endpoint);
	//socket_.set_option(asio::ip::multicast::join_group(multicast_addr));

	boost::asio::ip::address_v4 sourceAddress = boost::asio::ip::address_v4::from_string("192.169.0.101");
	boost::asio::ip::udp::endpoint listen_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4::from_string("0.0.0.0"), 30004);

	add_source_membership_v4 op(boost::asio::ip::address_v4::from_string("232.11.11.11"), sourceAddress,
		boost::asio::ip::address_v4::from_string("0.0.0.0"));

	try
	{
		socket_.open(listen_endpoint.protocol());
		socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
		socket_.set_option(op);
		socket_.bind(listen_endpoint);
	}
	catch (std::exception& ex)
	{
		std::cout << "Set socket option failed, err=" << ex.what() << std::endl;
	}


	do_recv();
}

void Receiver::do_recv()
{
	buff_.fill(0);
	socket_.async_receive_from(boost::asio::buffer(buff_), endpoint_, [this](const system::error_code& ec, std::size_t len) {
		if (!ec) {
			//std::cout.write(buff_.data(), len);
			std::string value(buff_.data(), len);
			std::cout << "From: "<<endpoint_.address().to_string()/* << " Receiver: " << value */<< std::endl;
			do_recv();
		}
	});
}
